package miblab.school;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import miblab.school.SystemParameters;

public class Password extends Activity {

	private EditText mEdit1;
	private EditText mEdit2;
	private String username;
	private String password;
	private String userchk;
	private String pass;
	private static String masterpassword="ABCD";
	int flags = Base64.NO_WRAP | Base64.URL_SAFE;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scr2a);

		Chk(SystemParameters.path+"/School/Username.txt"); 

		Button next2 = (Button) findViewById(R.id.button1);
		mEdit1   = (EditText)findViewById(R.id.editText1);
		mEdit2   = (EditText)findViewById(R.id.editText2);
		next2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				username = mEdit1.getText().toString();
				password = mEdit2.getText().toString();
				try {
					userchk=Read(SystemParameters.path+"/School/Username.txt");
					pass=Read(SystemParameters.path+"/School/Password.txt");

				} 
				catch (Exception e3) {
					Toast.makeText(Password.this, "Setup First", Toast.LENGTH_SHORT).show();
					e3.printStackTrace();
				}	

				try {
					if((username.equals(decrypt(masterpassword,userchk))&&(password.equals(decrypt(masterpassword,pass)))))
					{

						Intent intent = new Intent(Password.this,LocationOptions.class);
						startActivity(intent);
					}
					else
					{
						Toast.makeText(Password.this, "Wrong User name or Password", Toast.LENGTH_LONG).show();
					}
				} 
				catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} 

		});
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}
	@Override
	public void onBackPressed() {
		//Log.d("CDA", "onBackPressed Called");
		Intent intent = new Intent(Password.this,ScreenSchoolActivity.class);
		startActivity(intent);
	}

	//********************************Password Encryption*****************************
	public static String encrypt(String seed, String cleartext) throws Exception {
		byte[] rawKey = getRawKey(seed.getBytes());
		byte[] result = encrypt(rawKey, cleartext.getBytes());
		return toHex(result);
	}
	//-----------------------------------------------------------------------------
	private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(clear);
		return encrypted;
	}


	//******************************Password Decrypt************************************
	public static String decrypt(String seed, String encrypted) throws Exception {
		byte[] rawKey = getRawKey(seed.getBytes());
		byte[] enc = toByte(encrypted);
		byte[] result = decrypt(rawKey, enc);
		return new String(result);
	}

	//-----------------------------------------------------------------------------

	private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(encrypted);
		return decrypted;
	}

	//******************************Other encryption/decryption stuff******************
	private static byte[] getRawKey(byte[] seed) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
		sr.setSeed(seed);
		kgen.init(128, sr); // 192 and 256 bits may not be available
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		return raw;
	}

	//-----------------------------------------------------------------------------    
	public static String toHex(String txt) {
		return toHex(txt.getBytes());
	}
	public static String fromHex(String hex) {
		return new String(toByte(hex));
	}
	//-----------------------------------------------------------------------------
	public static byte[] toByte(String hexString) {
		int len = hexString.length()/2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++)
			result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
		return result;
	}
	//-----------------------------------------------------------------------------
	public static String toHex(byte[] buf) {
		if (buf == null)
			return "";
		StringBuffer result = new StringBuffer(2*buf.length);
		for (int i = 0; i < buf.length; i++) {
			appendHex(result, buf[i]);
		}
		return result.toString();
	}
	private final static String HEX = "0123456789ABCDEF";
	private static void appendHex(StringBuffer sb, byte b) {
		sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
	}

	//**********************Write SD***************************************************	  
	public void SDWrite(String filename, String value)
	{

		try
		{
			File gpxfile = new File(filename);
			if(!gpxfile.exists())
			{
				gpxfile.mkdirs();
				FileWriter writer1 = new FileWriter(gpxfile);
				writer1.write("");
				writer1.close();
			}
			String aBuffer1 = "";
			//-------------------------------------------------------------------------------------				
			aBuffer1 += value;
			FileWriter writer = new FileWriter(gpxfile);
			writer.append(aBuffer1);
			writer.close();


		} 
		//-------------------------------------------------------------------------------------			
		catch(IOException e)
		{
			Toast.makeText(this, "Insert SD Card", Toast.LENGTH_SHORT).show();
			e.printStackTrace();


		}



	}

	//********************Read*************************************		  
	public String Read(String filename)
	{

		String aDataRow = "";  
		//-------------------------------------------------------------------------------------			
		try
		{

			File gpxfile = new File(filename);
			if(!gpxfile.exists())
			{
				//Toast.makeText(this, "Set new user name & password", Toast.LENGTH_SHORT).show();
				username = mEdit1.getText().toString();
				password = mEdit2.getText().toString();
				String u = null;
				String p = null;
				try {
					u = encrypt(masterpassword,username);
					p = encrypt(masterpassword,password);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


				SDWrite(SystemParameters.path+"/School/Username.txt",u);
				SDWrite(SystemParameters.path+"/School/Password.txt",p);

			}
			FileInputStream fIn = new FileInputStream(gpxfile);
			BufferedReader myReader = new BufferedReader(
					new InputStreamReader(fIn));

			aDataRow = myReader.readLine();
			myReader.close();
			fIn.close();

			//-------------------------------------------------------------------------------------				

		} 
		//-------------------------------------------------------------------------------------			
		catch(IOException e)
		{
			Toast.makeText(this, "Insert SD Card 2", Toast.LENGTH_SHORT).show();
			e.printStackTrace();

		}
		return aDataRow;

	}

	public void Chk(String filename)
	{
		//-------------------------------------------------------------------------------------			
		try
		{

			File gpxfile = new File(filename);
			if(!gpxfile.exists())
			{
				Toast.makeText(this, "Set new user name & password", Toast.LENGTH_SHORT).show();

			}

		}
		catch(Exception e)
		{
			Toast.makeText(this, "Insert SD Card", Toast.LENGTH_SHORT).show();
			e.printStackTrace();

		}

	}
}

